package com.example.developerlab;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class TextViewSpanActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_textviewspan);
		TextView tv = findViewById(R.id.tv_testContent);
		String clickString = "《用户须知》"; // 设置文本点击事件
		String message = tv.getText().toString();
		SpannableStringBuilder builder = new SpannableStringBuilder(message);
		builder.setSpan(new ClickableSpan() {
							@Override
							public void onClick(@NonNull View widget) {
								Toast.makeText(TextViewSpanActivity.this,
										getResources().getText(R.string.warning_content),
										Toast.LENGTH_SHORT).show();
							}

							@Override
							public void updateDrawState(@NonNull TextPaint ds) {
								ds.setColor(ds.linkColor);
								// 删除下划线
								ds.setUnderlineText(false);
							}
						}
				, message.indexOf(clickString),
				message.indexOf(clickString) + clickString.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		String boldString = "尊敬的用户："; // 设置文本加粗
		builder.setSpan(new StyleSpan(Typeface.BOLD), message.indexOf(boldString),
				message.indexOf(boldString) + boldString.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		tv.setMovementMethod(LinkMovementMethod.getInstance());
		tv.setHighlightColor(getResources().getColor(R.color.purple_700, getTheme()));
		tv.setText(builder);
	}
}
